package isquirrel;

import isquirrel.beans.Friend;
import isquirrel.beans.User;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class FacebookAPI {

	String sessionkey = null;
	String apikey = "748303a5c47afd1a0823809e012c155e";
	String secret = "da1aa4c61222d5877d634941295b5d79";
	TinyFBClient _client = null;
    TreeMap<String, String> _callparams = null;

	
	public FacebookAPI(String sessionkey){
		this();
		this.sessionkey = sessionkey;
	}
	
	public FacebookAPI(){
		this._client = new TinyFBClient(apikey,secret);
		this._callparams = new TreeMap<String,String>();
	}
	
	public String getUser_PicSquare(String fbID){
		        
        JSONArray fieldArray = new JSONArray();
        fieldArray.put("pic_square");
        	
        _callparams.put("uids",fbID);
        _callparams.put("fields",fieldArray.toString());
       // tm.put("method","friends.get");
        
        JSONArray jsonstring = null;
        try {
			 jsonstring = new JSONArray(_client.call("users.getInfo", _callparams));
		} catch (JSONException e) {
			return null;
		}
		
		String picsquare = null;
		
		try {
			picsquare = jsonstring.getJSONObject(0).getString("pic_square");
		} catch (JSONException e) {
			return null;
		}
		
		_callparams.clear();
		if (picsquare.equals("null")){
			return null;
		}

		return picsquare;

	}
	
	public HashMap<Long,String> getUsers_PicSquare(Collection<User> users){
		
		ArrayList<String> auids = new ArrayList<String>();
		HashMap<Long,String> userpics = new HashMap<Long,String>();
		
		for (User u: users){
			if (u.getFbID() != 0L){
				auids.add(String.valueOf(u.getFbID()));
			}
			else{
				String pic = (u.getSex().equals("Male")) ? "nopicmale.png" : "nopicfemale.png";
				userpics.put(u.getUserID(),pic);
			}
		}
		
		JSONArray fieldArray = new JSONArray();
		fieldArray.put("pic_square");
		_callparams.put("uids",auids.toString());
		_callparams.put("fields",fieldArray.toString());
		    
		if (auids.size() == 0) { return userpics;} // the search query returned no-fb users, no need to go further
		
		String pics = _client.call("users.getInfo", _callparams);
		  
		JSONArray json_pics = null;
		try {
			json_pics = new JSONArray(pics);
		} catch (JSONException e) {
			return null;
		}
		
		Iterator<User> iter = users.iterator();

		try{
			while(iter.hasNext()){
				User user = iter.next();
				if (user.getFbID() == 0L) continue;
				JSONObject pic = findPic(user.getFbID(),json_pics);
				if (pic == null){
					throw new JSONException("User pic not found");
				}
				String picstr = pic.getString("pic_square");
				if (picstr.equals("null")){
					picstr = (user.getSex().equals("Male")) ? "nopicmale.png" : "nopicfemale.png"; 
				}
				userpics.put(user.getUserID(),picstr);
			}	
		}
		catch (JSONException e) {
			return null;
		}
	
		_callparams.clear();
		return userpics;

	}
	
	public Vector<Friend> getUser_FBFriends(User crnt_user){
		
		Set<User> userfriends = crnt_user.getFriends();
		userfriends.size();
		
		HashMap<Long,String> userid_fbid_pairs = new HashMap<Long,String>();
	
		for (User u : userfriends){
			if (u.getFbID() != 0L){
				userid_fbid_pairs.put(u.getUserID(),String.valueOf(u.getFbID()));
			}
		
		}

		ArrayList<String> auids = new ArrayList<String>(userid_fbid_pairs.values());
		Collections.shuffle(auids);
		
	    JSONArray fieldArray = new JSONArray();
	    fieldArray.put("pic_square");
	    _callparams.put("uids",auids.toString());
	    _callparams.put("fields",fieldArray.toString());
	    
	    String pics = _client.call("users.getInfo", _callparams);
	  
	    JSONArray json_pics = null;
	    try {
			json_pics = new JSONArray(pics);
		} catch (JSONException e) {
			return null;
		}
		
		Vector<Friend> result = new Vector<Friend>();
		
		Iterator<Long> iter = userid_fbid_pairs.keySet().iterator();
		try{
			while(iter.hasNext()){
				Long uid = iter.next();
				User u = UserManager.getUser(uid);
				JSONObject pic = findPic(u.getFbID(),json_pics);
				if (pic == null){
					throw new JSONException("User pic not found");
				}
				String picstr = pic.getString("pic_square");
				if (picstr.equals("null")){
					picstr = (u.getSex().equals("Male")) ? "nopicmale.png" : "nopicfemale.png"; 
				}
					result.add(new Friend(u.getFullName(),
									  u.getUserID(),
									  uid, 
									  picstr,
									  u.getLikedUrls().size(),
									  crnt_user.compare(u)
									  ));						
			}
		}
		catch (JSONException e) {
			return null;
		}
	
		_callparams.clear();
		return result;

	}
	
	private JSONObject findPic(Long uid, JSONArray pics) throws JSONException{
		
		for (int i = 0; i < pics.length(); ++i){
			JSONObject o = pics.getJSONObject(i);
			if (o.getLong("uid") == uid){
				return o;
			}
		}
		return null;
	}
}
